import {testname,testpassword} from '../utils/reg.js'
import { ajax } from '../utils/utils.js'


// 获取元素
const form = document.querySelector('form');
const username = document.querySelector('.name');
const password = document.querySelector('.pwd');
const errBox = document.querySelector('.error');




//给表单绑定提交事件

form.addEventListener('submit',submitHandler)

async function submitHandler(e){
    e.preventDefault();  // 阻止默认行为


    // 获取表单数据
    const usernameVal = username.value.trim();
    const passwordVal = password.value;

    // 验证数据

    // 没有写用户名密码 
    if(!usernameVal || !passwordVal){
        return alert('用户名或密码不能为空');
    }

    if(!testname(usernameVal) || !testpassword(passwordVal)){
        return alert('用户名或密码格式不正确');
    }

    const info = await ajax({url:'/users/login',method:'POST',dataType:'json',data:{'username':usernameVal,'password':passwordVal}})
    // console.log(info);
    if(info.data.code === 0){
        return  errBox.classList.add('active');

    }


    window.localStorage.setItem('id',info.data.user.id);
    window.localStorage.setItem('token',info.data.token);


    window.location.href = '../views/index.html';

}